package com.polaris.live.dialog_fragment.magiclamp

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.R
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupMagicLampBinding
import com.polaris.live.net.payerService
import com.polaris.live.popup.MagicLampHistoryPopup
import com.polaris.live.popup.MagicLampTipsPopup
import com.polaris.live.resp.back_resp.PayerLampResp

/**
 * MagicLampPopup 神灯
 *
 * @author Created by 天晴 on 2024/11/22/027 17:42
 */
class MagicLampPopup : DialogFragment() {

    private lateinit var mBinding: PopupMagicLampBinding

    private var mPosition = 0 //当前位置

    private val mViewModel by viewModels<BaseViewModel>()

    private val mUserId by lazy { arguments?.getLong("userId") ?: -1 }
    private val mIsLive by lazy { arguments?.getBoolean("isLive") ?: false }
    private val mPayerLampResp by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable("data", PayerLampResp::class.java)
        } else {
            arguments?.getParcelable("data")
        }
    }
    private var mToGift: (() -> Unit)? = null
    fun setOnMToGift(l: () -> Unit) {
        mToGift = l
    }

    private val mCopperFragment by lazy {
        MagicLampFragment().apply {
            arguments = bundleOf(
                "data" to mPayerLampResp?.copperLamp,
                "userId" to mUserId,
                "isLive" to mIsLive
            )
            setListener {
                dismiss()
                mToGift?.invoke()
            }
        }
    }
    private val mSilverFragment by lazy {
        MagicLampFragment().apply {
            arguments = bundleOf(
                "data" to mPayerLampResp?.silverLamp,
                "userId" to mUserId,
                "isLive" to mIsLive
            )
            setListener {
                dismiss()
                mToGift?.invoke()
            }
        }
    }
    private val mGoldFragment by lazy {
        MagicLampFragment().apply {
            arguments = bundleOf(
                "data" to mPayerLampResp?.goldLamp,
                "userId" to mUserId,
                "isLive" to mIsLive
            )
            setListener {
                dismiss()
                mToGift?.invoke()
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = PopupMagicLampBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(this)
            .transparentBar()
            .navigationBarDarkIcon(false)
            .init()

        val bottomView = mBinding.vLine
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp

        initView()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), android.R.style.Theme_Light_NoTitleBar_Fullscreen)
        val window = dialog.window
        window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return dialog
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            setWindowAnimations(R.style.BottomDialogAnimation)
        }
    }

    fun initView() {
        val mFragments = arrayListOf(mCopperFragment, mSilverFragment, mGoldFragment)
        mBinding.viewpager2.adapter = ViewPagerAdapter(mFragments, this)
        initDataView()
        mBinding.actMarquee.getActivitiesScroll(mViewModel, mUserId)
        initListener()
        mBinding.pagSilver.apply {
            path = PagConst.MAGIC_LAMP_SILVER
            setRepeatCount(-1)
        }
        mBinding.pagCopper.apply {
            path = PagConst.MAGIC_LAMP_COPPER
            setRepeatCount(-1)
        }
        mBinding.pagGold.apply {
            path = PagConst.MAGIC_LAMP_GOLD
            setRepeatCount(-1)
        }
    }

    private fun initListener() {
        mBinding.root.setOnSingleClickListener {
            dismiss()
        }
        mBinding.magicCl.setOnSingleClickListener {
        }
        mBinding.clickView.setOnClickListener {
            dismiss()
        }
        mBinding.viewpager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mPosition = position
                setPag()
            }
        })
        mBinding.btnWhat.setOnSingleClickListener {
            MagicLampTipsPopup.show(requireContext())
        }
        mBinding.btnSetting.setOnSingleClickListener {
            MagicLampHistoryPopup.show(requireContext(), mViewModel)
        }
        mBinding.copperFl.setOnSingleClickListener {
            mPosition = 0
            mBinding.viewpager2.currentItem = mPosition
            setPag()
        }
        mBinding.silverFl.setOnSingleClickListener {
            mPosition = 1
            mBinding.viewpager2.currentItem = mPosition
            setPag()
        }
        mBinding.goldFl.setOnSingleClickListener {
            mPosition = 2
            mBinding.viewpager2.currentItem = mPosition
            setPag()
        }
    }

    private fun setPag() {
        val payerLampResp = mPayerLampResp

        if (payerLampResp == null) return

        if (payerLampResp.copperLamp.status == 2L) {
            mBinding.pagCopper.visibility = View.GONE
            mBinding.imgCopper.visibility = View.VISIBLE
            mBinding.imgCopper.setImageResource(R.drawable.magic_lamp_copper_neck_small)
        } else {
            mBinding.pagCopper.visibility = View.VISIBLE
            mBinding.imgCopper.visibility = View.GONE
        }
        if (payerLampResp.silverLamp.status == 2L) {
            mBinding.pagSilver.visibility = View.GONE
            mBinding.imgSilver.visibility = View.VISIBLE
            mBinding.imgSilver.setImageResource(R.drawable.magic_lamp_silver_neck_small)
        } else {
            mBinding.pagSilver.visibility = View.VISIBLE
            mBinding.imgSilver.visibility = View.GONE
        }
        if (payerLampResp.goldLamp.status == 2L) {
            mBinding.pagGold.visibility = View.GONE
            mBinding.imgGold.visibility = View.VISIBLE
            mBinding.imgGold.setImageResource(R.drawable.magic_lamp_gold_neck_small)
        } else {
            mBinding.pagGold.visibility = View.VISIBLE
            mBinding.imgGold.visibility = View.GONE
        }

        when (mPosition) {
            0 -> {
                mBinding.copperFl.apply {
                    scaleX = 1.5f
                    scaleY = 1.5f
                }
                mBinding.silverFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                mBinding.goldFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                if (payerLampResp.copperLamp.status == 2L) {
                    mBinding.imgCopper.setImageResource(R.drawable.magic_lamp_copper_neck_big)
                } else {
                    mBinding.pagCopper.play()
                }
                mBinding.pagSilver.play()
                mBinding.pagGold.play()
            }

            1 -> {
                mBinding.copperFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                mBinding.silverFl.apply {
                    scaleX = 1.5f
                    scaleY = 1.5f
                }
                mBinding.goldFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                if (payerLampResp.silverLamp.status == 2L) {
                    mBinding.imgSilver.setImageResource(R.drawable.magic_lamp_silver_neck_big)
                } else {
                    mBinding.pagSilver.play()
                }
                mBinding.pagCopper.play()
                mBinding.pagGold.play()
            }

            2 -> {
                mBinding.copperFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                mBinding.silverFl.apply {
                    scaleX = 1f
                    scaleY = 1f
                }
                mBinding.goldFl.apply {
                    scaleX = 1.5f
                    scaleY = 1.5f
                }
                if (payerLampResp.goldLamp.status == 2L) {
                    mBinding.imgGold.setImageResource(R.drawable.magic_lamp_gold_neck_big)
                } else {
                    mBinding.pagGold.play()
                }
                mBinding.pagCopper.play()
                mBinding.pagSilver.play()
            }

        }

    }

    private fun initDataView() {
        val payerLampResp = mPayerLampResp

        if (payerLampResp == null) return
        val lampStatus = listOf(
            payerLampResp.copperLamp.status,
            payerLampResp.silverLamp.status,
            payerLampResp.goldLamp.status
        )
        mPosition = lampStatus.indexOfFirst { it == 1L }.takeIf { it >= 0 } ?: mPosition
        mBinding.viewpager2.setCurrentItem(mPosition, false)
        setPag()
    }

    companion object {

        private fun getLamp(mViewModel: BaseViewModel, userId: Long, back: (mPayerLampResp: PayerLampResp) -> Unit) {
            mViewModel.request({
                payerService.getLamp(userId)
            }, {
                back.invoke(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        fun show(
            context: Fragment,
            mViewModel: BaseViewModel,
            userId: Long,
            isLive: Boolean,
            toGift: (() -> Unit)? = null,
        ) {
            getLamp(mViewModel, userId) {
                val fragmentManager = context.parentFragmentManager
                MagicLampPopup().apply {
                    arguments = bundleOf(
                        "userId" to userId, "isLive" to isLive, "data" to it
                    )
                    setOnMToGift { toGift?.invoke() }
                }.show(fragmentManager, "MagicLampPopup")
            }
        }
    }
}